/*
 * This file is part of the Marmalade SDK Code Samples.
 *
 * (C) 2001-2012 Marmalade. All Rights Reserved.
 *
 * This source code is intended only as a supplement to the Marmalade SDK.
 *
 * THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
 * KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
 * PARTICULAR PURPOSE.
 */

// Standard includes
#include "IwUILabel.h"
#include "IwUILayoutGrid.h"
#include "IwUITableView.h"
#include "IwUITableViewItemSource.h"
#include "s3eContacts.h"

// Project includes
#include "IwUIDailyReport.h"

// VNThanh
#include "CppSqlWrapper.h"
#include "s3eFile.h"

class CAddHandler;
const char* DB_FILE_NAME = "sqlite.sdb";
SqlDatabase* dbProvider;

//-----------------------------------------------------------------------------

class CContactsItemSource : public CIwUITableViewItemSource,
    public IContactsItemSource
{
public:
    IW_MANAGED_DECLARE(CContactsItemSource)
    CContactsItemSource() :
        m_Active(false),
        m_ColumnWidth(-1),
        m_RowHeight(-1),
        m_Template(NULL),
        m_TemplateClone(NULL)
    {
    }

    virtual ~CContactsItemSource()
    {
        IwAssert(UI, !m_TemplateClone);
        delete m_Template;
    }

private:
    // IwManaged virtuals
    virtual void ParseCloseChild(CIwTextParserITX* pParser, CIwManaged* pChild)
    {
        m_Template = IwSafeCast<CIwUIElement*>(pChild);
    }

    virtual void Serialise()
    {
        CIwUITableViewItemSource::Serialise();

        IwSerialiseManagedObject(*(CIwManaged**)&m_Template);
    }

    virtual void Resolve()
    {
        CIwUITableViewItemSource::Resolve();

        CIwManaged* pTemplate = m_Template;
        if (pTemplate)
        {
            pTemplate->Resolve();
        }
    }

    // IwUITableViewItemSource virtuals
    virtual bool IsRowAvailable(int32 row) const
    {
        return (0 <= row) && (row < (int32)m_ContactUIDs.size());
    }

    virtual CIwUIElement* CreateItem(int32 row)
    {
        IwAssert(UI, IsRowAvailable(row));

        const int32 uid = m_ContactUIDs[row];

        // Store UID with item for future reference contactUID
        CIwUIElement* pItem = m_Template->Clone();
        pItem->SetProperty("contactUID", uid);


        // Set labels within template
		SqlStatement select = dbProvider->sqlQuery("select RowId, TaskName, BeginDate, StartTime, EndTime, Duration from DailyReport where RowId=?");
		select.bind(uid);
		select.execute();
		if(!select.hasRow())
		return;
		do
		{
			const SqlStatement::ResultRow& row = select.currentRow();
			CIwUILabel* col0;
			pItem->LookupChildNamed(col0,"TaskValue");
			col0->SetCaption(row.getStringField("TaskName"));
			CIwUILabel* col1;
			pItem->LookupChildNamed(col1,"StartTimeVal");
			col1->SetCaption(row.getStringField("StartTime"));
			CIwUILabel* col2;
			pItem->LookupChildNamed(col2,"EndTimeVal");
			col2->SetCaption(row.getStringField("EndTime"));
			CIwUILabel* col3;
			pItem->LookupChildNamed(col3,"DurationVal");
			col3->SetCaption(row.getStringField("Duration"));
		}while(select.nextRow());
		select.destroy();
        

        // Use unique identifier to create unique name
       

        return pItem;
    }

    virtual void ReleaseItem(CIwUIElement* pItem, int32 row)
    {
        delete pItem;
    }

    virtual int32 GetRowHeight(int32 row, int32 columnWidth) const
    {
        IwAssert(UI, IsRowAvailable(row));

        if (m_ColumnWidth != columnWidth)
        {
            CIwVec2 itemSize =
                m_TemplateClone->Measure(CIwVec2(columnWidth, LAYOUT_INFINITY));
            m_ColumnWidth = columnWidth;
            m_RowHeight = itemSize.y;
        }

        return m_RowHeight;
    }

    virtual void Activate(bool val)
    {
        CIwUITableViewItemSource::Activate(val);

        if (val)
        {
            if (!s3eContactsAvailable())
            {
                IwError(("Contacts are not available"));
            }

            // Clone template item into table (making invisible)
            // so we can determine its size.
            m_TemplateClone = m_Template->Clone();
            m_TemplateClone->SetVisible(false);
            GetTableView()->AddChild(m_TemplateClone);

            // Attach to application
            GetApp()->SetActiveItemSource(this);

            // Cache UIDs
			if (s3eFileCheckExists(DB_FILE_NAME) == S3E_TRUE)
			{
				dbProvider = new SqlDatabase(DB_FILE_NAME, false);
				UpdateAllUIDs();
			}
        }
        else
        {
			// VNThanh
			if(dbProvider)
			{
				dbProvider->close();
				delete dbProvider;
			}
            GetApp()->SetActiveItemSource(NULL);
            m_ContactUIDs.clear();

            GetTableView()->RemoveChild(m_TemplateClone);
            delete m_TemplateClone;
            m_TemplateClone = NULL;
        }

        m_ColumnWidth = -1;
        m_RowHeight = -1;
        m_Active = val;
    }

    virtual void Clone(CIwUITableViewItemSource* pTarget) const
    {
        IW_UI_CLONE_SUPERCLASS(pTarget, CContactsItemSource, CIwUITableViewItemSource);

        CContactsItemSource* pItemSource = (CContactsItemSource*) pTarget;
        pItemSource->m_Template = m_Template->Clone();
    }

    // ContactsItemSource virtuals
    virtual int32 GetUID(int32 index)
    {
        return (0 <= index) && (index < (int32)m_ContactUIDs.size()) ?
            m_ContactUIDs[index] : -1;
    }

    virtual void CreatedUID(int32 uid)
    {
        IwAssertMsg(UI, !m_ContactUIDs.contains(uid),
            ("Already have contact for that uid"));

        // Add item at end
        int32 index = m_ContactUIDs.size();
        m_ContactUIDs.insert_slow(uid, index);

        if (m_Active)
        {
            // Tell table of new row
            GetTableView()->InsertRow(index);

            // Show new contact
            GetTableView()->SetSelection(index);
            GetTableView()->SetScrollToRow(index);
        }
    }

    virtual void UpdatedUID(int32 uid)
    {
        // Find index for UID
        int32 index = m_ContactUIDs.find(uid);

        if (index != -1)
        {
            if (m_Active)
            {
                // Tell table to update row
                GetTableView()->UpdateRow(index);
            }
        }
    }

    virtual void DeletedUID(int32 uid)
    {
        // Find index for UID
        int32 index = m_ContactUIDs.find(uid);

        if (index != -1)
        {
            m_ContactUIDs.erase(index);

            if (m_Active)
            {
                // Tell table to remove row
                GetTableView()->DeleteRow(index);
            }
        }
    }

    //virtual void UpdateAllUIDs()
    //{
    //    m_ContactUIDs.clear();

    //    // Read all contact UIDs
    //    s3eContactsUpdate();
    //    int32 numContacts = s3eContactsGetNumRecords();
    //    for (int32 i=0; i<numContacts; ++i)
    //    {
    //        const int32 uid = s3eContactsGetUID(i);
    //        IwAssertMsg(UI, uid != -1, ("Invalid UID"));
    //        if (uid != -1)
    //        {
    //            m_ContactUIDs.push_back(uid);
    //        }
    //    }

    //    if (m_Active)
    //    {
    //        // Tell table to rebuild all items
    //        GetTableView()->RecreateItemsFromSource();
    //    }
    //}

void addDataItem(const int RowId, const char* pFirstName, const char* pLastName, const char* pMobileNumber)
{

	CIwUIElement* pItem = m_Template->Clone();
	//pItem->SetProperty("rowId", RowId);
	CIwUILabel* col0;
	pItem->LookupChildNamed(col0,"FirstValue");
	col0->SetCaption(pFirstName);
	CIwUILabel* col1;
	pItem->LookupChildNamed(col1,"LastValue");
	col1->SetCaption(pLastName);
	CIwUILabel* col2;
	pItem->LookupChildNamed(col1,"MobileValue");
	col1->SetCaption(pMobileNumber);
}

virtual void UpdateAllUIDs()
{
    // select all order by RowId
	SqlStatement select = dbProvider->sqlQuery("select RowId, TaskName, BeginDate, StartTime, EndTime, Duration from DailyReport order by RowId desc");
	if(!select.hasRow())
		return;
	do
	{
		const SqlStatement::ResultRow& row = select.currentRow();
		//addDataItem(row.getIntField("RowId"), row.getStringField("FirstName"), row.getStringField("LastName"), row.getStringField("MobileName"));
		int16 id = row.getIntField("RowId");
		m_ContactUIDs.push_back(row.getIntField("RowId"));
	}while(select.nextRow());
	select.destroy();
	//SqlStatement selectcount = dbProvider->sqlQuery("select count(*) as numRecord from DailyReport");
	
	//int32 numRecord = dbProvider->getScalar("select count(*) from contact", 7);
}

		// Member data
		bool                m_Active;
		mutable int32       m_ColumnWidth;
		mutable int32       m_RowHeight;
		CIwUIElement*       m_Template;
		CIwUIElement*       m_TemplateClone;
		CIwArray<int32>     m_ContactUIDs;
};

IW_MANAGED_IMPLEMENT_FACTORY(CContactsItemSource);
